﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using System.Collections;
using Infragistics.Win.UltraWinGrid;
using Infragistics.Win;

namespace BYManageInfoSystem
{
    public partial class Frm_FeeShouldRecvTrueRecvTab : DockContent
    {
        private DGBY.BLL.FeeShouldRecvTrueRecvTab m_FeeShouldRecvTrueRecvTab = new DGBY.BLL.FeeShouldRecvTrueRecvTab();
        private DGBY.BLL.FactoryDataTab m_bllFactoryDataTab = new DGBY.BLL.FactoryDataTab();

        private DataSet m_dsFacData = null;

        public Frm_FeeShouldRecvTrueRecvTab()
        {
            InitializeComponent();
        }

        private void buttonShowAll_Click(object sender, EventArgs e)
        {
            int nNow = Convert.ToInt32(DateTime.Now.ToString("yyyyMM"));

            GenerateFeeShouldRecvTrueRecvDate(nNow);
            ShowAllRecord("");
        }

        private void ShowAllRecord(string strWhere)
        {
            ultraGrid1.DataSource = null;
            DataSet ds = m_FeeShouldRecvTrueRecvTab.ShyowShouldRecvTrueRecvTab(strWhere);

            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                ultraGrid1.DataSource = ds.Tables[0];
                ultraGrid1.DisplayLayout.Bands[0].Columns["FactoryDataTabID"].Hidden = true;
          
                for (int i = 0; i < ds.Tables[0].Rows.Count; ++i)
                {
                    for (int j = 0; j < this.ultraGrid1.DisplayLayout.Bands[0].Columns.Count; ++j)
                    {
                        if(j != 7 && j != 9)
                        ultraGrid1.Rows[i].Cells[j].Activation = Infragistics.Win.UltraWinGrid.Activation.ActivateOnly;
                    }
                }
            }
        }
        
        private void GenerateFeeShouldRecvTrueRecvDate(int nNow)
        {
            try
            {
                int nMaxYearMonth = GetMaxShouldRecvTrueRecvYearMonth();

                if (nMaxYearMonth == 0)
                {
                    nMaxYearMonth = 201206;
                }
                else
                {
                    AddYearMonth(ref nMaxYearMonth);
                }

                if (m_dsFacData.Tables.Count > 0 && m_dsFacData.Tables[0].Rows.Count > 0)
                {
                    int nCount = 0;
                    int nBeginYearMonth = nMaxYearMonth;
                    for (; 0 <= CompareYearMonth(nNow, nMaxYearMonth); AddYearMonth(ref nMaxYearMonth))
                    {
                        for (int i = 0; i < m_dsFacData.Tables[0].Rows.Count; i++)
                        {
                            DGBY.Model.FeeShouldRecvTrueRecvTab modelFeeShouldRecvTrueRecv = new DGBY.Model.FeeShouldRecvTrueRecvTab()   ;
                            modelFeeShouldRecvTrueRecv.FactoryDataTabID = Convert.ToInt32(m_dsFacData.Tables[0].Rows[i]["FactoryDataTabID"].ToString());
                            modelFeeShouldRecvTrueRecv.FeeTrueReciveveDate = nMaxYearMonth;

                            DataSet ds = m_FeeShouldRecvTrueRecvTab.GetList("FactoryDataTabID = '" + modelFeeShouldRecvTrueRecv.FactoryDataTabID + "' and FeeTrueReciveveDate = '" + modelFeeShouldRecvTrueRecv.FeeTrueReciveveDate + "'");

                            if (ds.Tables.Count == 1 && ds.Tables[0].Rows.Count == 0)
                            {
                                modelFeeShouldRecvTrueRecv.IsClearingAccount = true;
                                modelFeeShouldRecvTrueRecv.FeeNote = "";

                                int nID = m_FeeShouldRecvTrueRecvTab.Add(modelFeeShouldRecvTrueRecv);
                                ds = m_FeeShouldRecvTrueRecvTab.ShyowShouldRecvTrueRecvTab("FactoryDataTabID = '" + modelFeeShouldRecvTrueRecv.FactoryDataTabID + "' and 应收费用年月 = '" + modelFeeShouldRecvTrueRecv.FeeTrueReciveveDate + "'");
                                Decimal dtTemp = (Decimal)ds.Tables[0].Rows[0]["差额"];
                                if (dtTemp != 0)
                                {
                                    DGBY.Model.FeeShouldRecvTrueRecvTab modelFeeShouldRecvTrueRecvNew = m_FeeShouldRecvTrueRecvTab.GetModel(modelFeeShouldRecvTrueRecv.FactoryDataTabID, modelFeeShouldRecvTrueRecv.FeeTrueReciveveDate);
                                    modelFeeShouldRecvTrueRecvNew.IsClearingAccount = false;
                                    m_FeeShouldRecvTrueRecvTab.Update(modelFeeShouldRecvTrueRecvNew);
                                }
                                ++nCount;
                            }
                        }
                    }

                    if (nCount > 0)
                    {
                        MessageBox.Show("最新生成从" + nBeginYearMonth + "到" + nNow + "共" + nCount + "条应收实收费用记录", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }


            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
        }

        private int GetMaxShouldRecvTrueRecvYearMonth()
        {
            int nMaxYearMonth = 0;

            DataSet ds = m_FeeShouldRecvTrueRecvTab.GetMaxYearMonth();
            if (ds.Tables[0].Rows[0]["maxYearMonth"].ToString() != "")
            {
                nMaxYearMonth = (int)ds.Tables[0].Rows[0]["maxYearMonth"];
            }

            return nMaxYearMonth;
        }

        private void Frm_FeeShouldRecvTrueRecvTab_Load(object sender, EventArgs e)
        {
            m_dsFacData = m_bllFactoryDataTab.GetList("");
        }

        private void AddYearMonth(ref int nNow)
        {
            int nNewYear = nNow / 100;
            int nNewMonth = nNow % 100;

            ++nNewMonth;
            if (nNewMonth > 12)
            {
                nNewMonth = 1;
                ++nNewYear;
            }

            nNow = nNewYear * 100 + nNewMonth;
        }

        private int CompareYearMonth(int nNow, int nMaxYearMonth)
        {
            int nRet = 0;

            int nNowYear = nNow / 100;
            int nNowMonth = nNow % 100;

            int nMaxYear = nMaxYearMonth / 100;
            int nMaxMonth = nMaxYearMonth % 100;

            if (nNowYear < nMaxYear)
            {
                nRet = -1;
            }
            else if (nNowYear > nMaxYear)
            {
                nRet = 1;
            }
            else
            {
                if (nNowMonth < nMaxMonth)
                {
                    nRet = -1;
                }
                else if (nNowMonth > nMaxMonth)
                {
                    nRet = 1;
                }
                else
                {
                    nRet = 0;
                }
            }

            return nRet;
        }

        private void ultraGrid1_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {

                case Keys.Up:
                    {
                        UltraGridCell gridCell = this.ultraGrid1.ActiveCell;
                        if (null == gridCell)
                            return;

                        int nColumnIndex = this.ultraGrid1.ActiveCell.Column.Index;
                        int nIndex = ultraGrid1.ActiveRow.Index;
                        if (nIndex > 0)
                            nIndex--;
                        this.ultraGrid1.PerformAction(UltraGridAction.ExitEditMode, false,
                          false);
                        this.ultraGrid1.PerformAction(UltraGridAction.AboveCell, false,
                          false);
                        e.Handled = true;
                        ultraGrid1.Rows[nIndex].Cells[nColumnIndex].IgnoreRowColActivation = true;
                        ultraGrid1.Rows[nIndex].Cells[nColumnIndex].Activation = Activation.AllowEdit;
                        ultraGrid1.Rows[nIndex].Cells[nColumnIndex].Activate();
                        this.ultraGrid1.PerformAction(UltraGridAction.EnterEditMode, false,
                          false);
                        break;
                    }

                case Keys.Down:
                    {
                        UltraGridCell gridCell = this.ultraGrid1.ActiveCell;
                        if (null == gridCell)
                            return;

                        int nColumnIndex = this.ultraGrid1.ActiveCell.Column.Index;
                        int nIndex = ultraGrid1.ActiveRow.Index;
                        if (nIndex < ultraGrid1.Rows.Count - 1)
                            nIndex++;
                        this.ultraGrid1.PerformAction(UltraGridAction.ExitEditMode, false,
                          false);
                        this.ultraGrid1.PerformAction(UltraGridAction.BelowCell, false,
                          false);
                        e.Handled = true;
                        ultraGrid1.Rows[nIndex].Cells[nColumnIndex].IgnoreRowColActivation = true;
                        ultraGrid1.Rows[nIndex].Cells[nColumnIndex].Activation = Activation.AllowEdit;
                        ultraGrid1.Rows[nIndex].Cells[nColumnIndex].Activate();
                        this.ultraGrid1.PerformAction(UltraGridAction.EnterEditMode, false,
                          false);
                        break;
                    }

                case Keys.Right:
                    this.ultraGrid1.PerformAction(UltraGridAction.ExitEditMode, false,
                      false);
                    this.ultraGrid1.PerformAction(UltraGridAction.NextCellByTab, false,
                      false);
                    e.Handled = true;
                    this.ultraGrid1.PerformAction(UltraGridAction.EnterEditMode, false,
                      false);
                    break;
                case Keys.Left:
                    this.ultraGrid1.PerformAction(UltraGridAction.ExitEditMode, false,
                      false);
                    this.ultraGrid1.PerformAction(UltraGridAction.PrevCellByTab, false,
                      false);
                    e.Handled = true;
                    this.ultraGrid1.PerformAction(UltraGridAction.EnterEditMode, false,
                      false);
                    break;
            }
        }

        private void ultraGrid1_BeforeRowUpdate(object sender, CancelableRowEventArgs e)
        {
            try
            {
                UltraGridRow CurrentUGR;
                CurrentUGR = ultraGrid1.Rows[e.Row.Index];

                ModifyGoodsDetail(e.Row.Index);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                e.Cancel = true;
            }
        }

        private bool ModifyGoodsDetail(int nRowIndex)
        {
            try
            {
                UltraGridRow CurrentUGR;
                CurrentUGR = ultraGrid1.Rows[nRowIndex];

                int nFactoryDataTabID = Convert.ToInt32(CurrentUGR.Cells["FactoryDataTabID"].Value.ToString(), 10);
                int nFeeTrueReciveveDate = Convert.ToInt32(CurrentUGR.Cells["应收费用年月"].Value.ToString(), 10);

                Boolean bIsClear = Convert.ToBoolean(CurrentUGR.Cells["是否抹账"].Value.ToString());
                string strNode = CurrentUGR.Cells["备注"].Value.ToString();
            
                DGBY.Model.FeeShouldRecvTrueRecvTab modelFeeShouldRecvTrueRecvTab = m_FeeShouldRecvTrueRecvTab.GetModel(nFactoryDataTabID, nFeeTrueReciveveDate);
                if (null != modelFeeShouldRecvTrueRecvTab)
                {
                    if (modelFeeShouldRecvTrueRecvTab.IsClearingAccount != bIsClear || modelFeeShouldRecvTrueRecvTab.FeeNote != strNode)
                    {
                        modelFeeShouldRecvTrueRecvTab.IsClearingAccount = bIsClear;
                        modelFeeShouldRecvTrueRecvTab.FeeNote = strNode;
                        m_FeeShouldRecvTrueRecvTab.Update(modelFeeShouldRecvTrueRecvTab);

                        ShowAllRecord("");
                    }
                }

                return true;

            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }
        public void InitUltraWinGridSetting()
        {
            this.ultraGrid1.DisplayLayout.Override.RowSelectors = Infragistics.Win.DefaultableBoolean.True;
            this.ultraGrid1.DisplayLayout.Override.RowSelectorNumberStyle = Infragistics.Win.UltraWinGrid.RowSelectorNumberStyle.VisibleIndex;
            this.ultraGrid1.DisplayLayout.Override.RowSelectorWidth = 40;
        }
        public static void ultraGrid1_InitializeRowFilter(Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
        {
            //ultraGrid1.DisplayLayout.Override.RowSizing = RowSizing.AutoFree;
            //foreach (UltraGridColumn ugc in ultraGrid1.DisplayLayout.Bands[0].Columns)
            //    ugc.PerformAutoResize();
            // FILTER ROW FUNCTIONALITY RELATED ULTRAGRID SETTINGS
            //e.Layout.Override.RowFilterAction = RowFilterAction.DisableFilteredOutRows;
            // ----------------------------------------------------------------------------------
            // Enable the the filter row user interface by setting the FilterUIType to FilterRow.
            e.Layout.Override.FilterUIType = FilterUIType.FilterRow;
            //e.Layout.Override.RowFilterMode = RowFilterMode.AllRowsInBand;
            // FilterEvaluationTrigger specifies when UltraGrid applies the filter criteria typed 
            // into a filter row. Default is OnCellValueChange which will cause the UltraGrid to
            // re-filter the data as soon as the user modifies the value of a filter cell.
            e.Layout.Override.FilterEvaluationTrigger = FilterEvaluationTrigger.OnCellValueChange;
            //e.Layout.Override.RowFilterMode = RowFilterMode.AllRowsInBand;
            // By default the UltraGrid selects the type of the filter operand editor based on
            // the column's DataType. For DateTime and boolean columns it uses the column's editors.
            // For other column types it uses the Combo. You can explicitly specify the operand
            // editor style by setting the FilterOperandStyle on the override or the individual
            // columns.

            e.Layout.Override.FilterOperandStyle = FilterOperandStyle.DropDownList;

            // By default UltraGrid displays user interface for selecting the filter operator. 
            // You can set the FilterOperatorLocation to hide this user interface. This
            // property is available on column as well so it can be controlled on a per column
            // basis. Default is WithOperand. This property is exposed off the column as well.
            e.Layout.Override.FilterOperatorLocation = FilterOperatorLocation.WithOperand;

            // By default the UltraGrid uses StartsWith as the filter operator. You use
            // the FilterOperatorDefaultValue property to specify a different filter operator
            // to use. This is the default or the initial filter operator value of the cells
            // in filter row. If filter operator user interface is enabled (FilterOperatorLocation
            // is not set to None) then that ui will be initialized to the value of this
            // property. The user can then change the operator as he/she chooses via the operator
            // drop down.
            e.Layout.Override.FilterOperatorDefaultValue = FilterOperatorDefaultValue.StartsWith;

            // FilterOperatorDropDownItems property can be used to control the options provided
            // to the user for selecting the filter operator. By default UltraGrid bases 
            // what operator options to provide on the column's data type. This property is
            // avaibale on the column as well.
            //e.Layout.Override.FilterOperatorDropDownItems = FilterOperatorDropDownItems.All;

            // By default UltraGrid displays a clear button in each cell of the filter row
            // as well as in the row selector of the filter row. When the user clicks this
            // button the associated filter criteria is cleared. You can use the 
            // FilterClearButtonLocation property to control if and where the filter clear
            // buttons are displayed.
            e.Layout.Override.FilterClearButtonLocation = FilterClearButtonLocation.RowAndCell;

            // Appearance of the filter row can be controlled using the FilterRowAppearance proeprty.
            e.Layout.Override.FilterRowAppearance.BackColor = Color.LightYellow;

            // You can use the FilterRowPrompt to display a prompt in the filter row. By default
            // UltraGrid does not display any prompt in the filter row.
            e.Layout.Override.FilterRowPrompt = "Click here to filter data...";

            // You can use the FilterRowPromptAppearance to change the appearance of the prompt.
            // By default the prompt is transparent and uses the same fore color as the filter row.
            // You can make it non-transparent by setting the appearance' BackColorAlpha property 
            // or by setting the BackColor to a desired value.
            e.Layout.Override.FilterRowPromptAppearance.BackColorAlpha = Alpha.Opaque;

            // By default the prompt is spread across multiple cells if it's bigger than the
            // first cell. You can confine the prompt to a particular cell by setting the
            // SpecialRowPromptField property off the band to the key of a column.
            //e.Layout.Bands[0].SpecialRowPromptField = e.Layout.Bands[0].Columns[0].Key;

            // Display a separator between the filter row other rows. SpecialRowSeparator property 
            // can be used to display separators between various 'special' rows, including for the
            // filter row. This property is a flagged enum property so it can take multiple values.
            e.Layout.Override.SpecialRowSeparator = SpecialRowSeparator.FilterRow;

            // You can control the appearance of the separator using the SpecialRowSeparatorAppearance
            // property.
            e.Layout.Override.SpecialRowSeparatorAppearance.BackColor = Color.FromArgb(233, 242, 199);

            //   UltraGridBand band = e.Layout.Bands[0];
            //   band.ColumnFilters["原币金额"].FilterConditions.Clear();
            //   band.ColumnFilters["原币金额"].FilterConditions.Add(

            //FilterComparisionOperator.GreaterThan, 5);
            //   band.ColumnFilters["原币金额"].FilterConditions.Add(

            //FilterComparisionOperator.LessThan, 10);
            //   band.ColumnFilters["原币金额"].LogicalOperator = FilterLogicalOperator.And;
        }
        private void ultraGrid1_InitializeLayout(object sender, InitializeLayoutEventArgs e)
        {
            if (this.checkBox1.Checked == true)
                ultraGrid1_InitializeRowFilter(e);
            else
                ClassUltraGridCommonSet.ultraGrid1_InitializeRowFilter(e);
            InitUltraWinGridSetting();

            SummarySettings averageSummary =
e.Layout.Bands[0].Summaries.Add(
"应收费用",
SummaryType.Sum,
e.Layout.Bands[0].Columns["应收费用"]);
            averageSummary.SummaryPosition = SummaryPosition.UseSummaryPositionColumn;
            averageSummary.SummaryPositionColumn = averageSummary.SourceColumn;
            averageSummary.DisplayFormat = "{0:.##}";
            averageSummary.Band.Override.SummaryFooterCaptionVisible = DefaultableBoolean.False;
            averageSummary.Band.Override.BorderStyleSummaryFooter = UIElementBorderStyle.None;
            averageSummary.SummaryDisplayArea = SummaryDisplayAreas.TopFixed;

            averageSummary =
 e.Layout.Bands[0].Summaries.Add(
 "实收金额",
 SummaryType.Sum,
 e.Layout.Bands[0].Columns["实收金额"]);
            averageSummary.SummaryPosition = SummaryPosition.UseSummaryPositionColumn;
            averageSummary.SummaryPositionColumn = averageSummary.SourceColumn;
            averageSummary.DisplayFormat = "{0:.##}";
            averageSummary.Band.Override.SummaryFooterCaptionVisible = DefaultableBoolean.False;
            averageSummary.Band.Override.BorderStyleSummaryFooter = UIElementBorderStyle.None;
            averageSummary.SummaryDisplayArea = SummaryDisplayAreas.TopFixed;

            averageSummary =
e.Layout.Bands[0].Summaries.Add(
"差额",
SummaryType.Sum,
e.Layout.Bands[0].Columns["差额"]);
            averageSummary.SummaryPosition = SummaryPosition.UseSummaryPositionColumn;
            averageSummary.SummaryPositionColumn = averageSummary.SourceColumn;
            averageSummary.DisplayFormat = "{0:.##}";
            averageSummary.Band.Override.SummaryFooterCaptionVisible = DefaultableBoolean.False;
            averageSummary.Band.Override.BorderStyleSummaryFooter = UIElementBorderStyle.None;
            averageSummary.SummaryDisplayArea = SummaryDisplayAreas.TopFixed;

            averageSummary =
e.Layout.Bands[0].Summaries.Add(
"应收未收金额",
SummaryType.Sum,
e.Layout.Bands[0].Columns["应收未收金额"]);
            averageSummary.SummaryPosition = SummaryPosition.UseSummaryPositionColumn;
            averageSummary.SummaryPositionColumn = averageSummary.SourceColumn;
            averageSummary.DisplayFormat = "{0:.##}";
            averageSummary.Band.Override.SummaryFooterCaptionVisible = DefaultableBoolean.False;
            averageSummary.Band.Override.BorderStyleSummaryFooter = UIElementBorderStyle.None;
            averageSummary.SummaryDisplayArea = SummaryDisplayAreas.TopFixed;
        }

        private void buttonExportToExcel_Click(object sender, EventArgs e)
        {
            DataTable dt = (DataTable)ultraGrid1.DataSource;

            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                {
                    SaveFileDialog sfd = new SaveFileDialog();
                    sfd.Filter = "Excel文件(*.xls)|*.xls";
                    string outFile = "";

                    if (sfd.ShowDialog() == DialogResult.OK)
                    {
                        outFile = sfd.FileName;
                    }
                    else
                    {
                        return;
                    }

                    ultraGridExcelExporter1.Export(ultraGrid1, outFile);
                }
            }
        }
    }
}
